<template>
  <div class="quality-monitor-container">
    <div class="page-header">
      <el-button icon="el-icon-back" @click="goBack">返回主页</el-button>
    </div>
    <el-card class="quality-search-card">
      <div slot="header" class="card-header">
        <h3><i class="el-icon-search"></i> 产品质量溯源查询</h3>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input 
            v-model="searchForm.traceCode" 
            placeholder="请输入溯源码" 
            clearable 
            prefix-icon="el-icon-collection-tag"
            @keyup.enter.native="searchByTraceCode">
            <el-button 
              slot="append" 
              icon="el-icon-search" 
              @click="searchByTraceCode" 
              :loading="searching">
              查询
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch" plain>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-if="qualityData" class="quality-detail-card">
      <div class="product-container">
        <div class="product-header">
          <h2>{{ qualityData.productName }}</h2>
          <div class="status-tags">
            <el-tag :type="qualityData.temperatureSafe ? 'success' : 'danger'" size="medium">
              {{ qualityData.temperatureSafe ? '温度正常' : '温度异常' }}
            </el-tag>
            <el-tag :type="getStatusType(qualityData.auditStatus)" size="medium" style="margin-left: 10px;">
              {{ getAuditStatusText(qualityData.auditStatus) }}
            </el-tag>
          </div>
        </div>
        
        <div class="product-content">
          <div class="product-main">
            <div class="product-image">
              <i class="el-icon-goods product-icon"></i>
            </div>
            <div class="product-info">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="产品编号">{{ qualityData.productId }}</el-descriptions-item>
                <el-descriptions-item label="溯源码">{{ qualityData.traceCode }}</el-descriptions-item>
                <el-descriptions-item label="产地">{{ qualityData.origin }}</el-descriptions-item>
                <el-descriptions-item label="收获时间">{{ formatTime(qualityData.harvestTime) }}</el-descriptions-item>
                <el-descriptions-item label="认证时间">{{ formatTime(qualityData.certifyTime) }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          
          <div class="product-details">
            <div class="detail-section">
              <h4><i class="el-icon-temperature"></i> 温度监控</h4>
              <div class="temperature-info">
                <div class="temp-range">
                  <span class="info-label">温度范围：</span>
                  <el-tag type="info">{{ qualityData.minTemp }}°C ~ {{ qualityData.maxTemp }}°C</el-tag>
                </div>
                <div class="transport-score">
                  <span class="info-label">运输评分：</span>
                  <el-rate
                    v-model="transportScore"
                    disabled
                    show-score
                    text-color="#ff9900">
                  </el-rate>
                </div>
                <div class="temp-record" v-if="isAdmin">
                  <el-form :inline="true" :model="tempRecordForm">
                    <el-form-item label="当前温度">
                      <el-input-number 
                        v-model="tempRecordForm.temperature" 
                        :precision="1" 
                        :step="0.5"
                        :min="-50"
                        :max="100"
                        placeholder="请输入温度值">
                      </el-input-number>
                      <span class="unit">°C</span>
                    </el-form-item>
                    <el-form-item>
                      <el-button 
                        type="primary" 
                        size="small" 
                        @click="submitTempRecord"
                        :loading="submittingTemp">
                        记录温度
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="quality-status" v-if="qualityStatus">
                  <h5>质量检测结果</h5>
                  <div class="status-item">
                    <span class="info-label">最低记录温度：</span>
                    <el-tag 
                      :type="qualityStatus.minRecordedTemp < qualityData.minTemp ? 'danger' : 'info'">
                      {{ qualityStatus.minRecordedTemp }}°C
                    </el-tag>
                    <span class="temp-warning" v-if="qualityStatus.minRecordedTemp < qualityData.minTemp">
                      <i class="el-icon-warning"></i> 低于安全值
                    </span>
                  </div>
                  <div class="status-item">
                    <span class="info-label">最高记录温度：</span>
                    <el-tag 
                      :type="qualityStatus.maxRecordedTemp > qualityData.maxTemp ? 'danger' : 'info'">
                      {{ qualityStatus.maxRecordedTemp }}°C
                    </el-tag>
                    <span class="temp-warning" v-if="qualityStatus.maxRecordedTemp > qualityData.maxTemp">
                      <i class="el-icon-warning"></i> 高于安全值
                    </span>
                  </div>
                  <div class="status-item">
                    <span class="info-label">质量状态：</span>
                    <el-tag :type="qualityStatus.isQualified ? 'success' : 'danger'">
                      {{ qualityStatus.isQualified ? '合格' : '不合格' }}
                    </el-tag>
                    <span class="last-check" v-if="qualityStatus.lastCheckTime">
                      最后检查：{{ formatTime(qualityStatus.lastCheckTime) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <h4><i class="el-icon-document-checked"></i> 审核信息</h4>
              <div class="audit-info">
                <div class="status-item">
                  <span class="info-label">审核状态：</span>
                  <el-tag :type="getStatusType(qualityData.auditStatus)" size="medium">
                    {{ getAuditStatusText(qualityData.auditStatus) }}
                  </el-tag>
                </div>
                <div class="audit-comment-box">
                  <span class="info-label">审核意见：</span>
                  <p class="audit-comment">{{ qualityData.auditComment || '暂无审核意见' }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <el-card v-if="isAdmin" class="quality-create-card">
      <div slot="header" class="card-header">
        <h3>创建质量记录</h3>
      </div>
      <el-form :model="newRecordForm" :rules="rules" ref="newRecordForm" label-width="100px" class="create-form">
        <div class="form-row">
          <el-form-item label="产品ID" prop="productId">
            <el-input v-model.number="newRecordForm.productId" type="number" placeholder="请输入产品唯一ID"></el-input>
          </el-form-item>
          <el-form-item label="溯源码" prop="traceCode">
            <el-input v-model="newRecordForm.traceCode" placeholder="请输入产品溯源码"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="newRecordForm.productName" placeholder="请输入产品名称"></el-input>
          </el-form-item>
          <el-form-item label="产地" prop="origin">
            <el-input v-model="newRecordForm.origin" placeholder="请输入产品产地"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="收获时间" prop="harvestTimeDate">
            <el-date-picker
              v-model="newRecordForm.harvestTimeDate"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              :clearable="false">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="温度范围" required>
            <div class="temp-inputs">
              <el-form-item prop="minTemp" class="no-margin">
                <el-input-number 
                  v-model="newRecordForm.minTemp" 
                  :precision="1" 
                  :step="0.5"
                  :min="-50" 
                  :max="100" 
                  placeholder="最低温度">
                </el-input-number>
              </el-form-item>
              <span class="temp-separator">~</span>
              <el-form-item prop="maxTemp" class="no-margin">
                <el-input-number 
                  v-model="newRecordForm.maxTemp" 
                  :precision="1" 
                  :step="0.5"
                  :min="-50" 
                  :max="100" 
                  placeholder="最高温度">
                </el-input-number>
              </el-form-item>
              <span class="unit">°C</span>
            </div>
          </el-form-item>
        </div>
        <el-form-item class="form-buttons">
          <el-button type="primary" @click="submitForm" :loading="submitting">创建记录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-if="qualityData && isAdmin && qualityData.auditStatus === 0" class="quality-audit-card">
      <div slot="header" class="card-header">
        <h3><i class="el-icon-s-check"></i> 手动审核</h3>
      </div>
      <el-form :model="auditForm" ref="auditForm" label-width="100px" class="audit-form">
        <el-form-item label="审核状态" required>
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">
              <el-tag type="success" size="small">通过</el-tag>
            </el-radio>
            <el-radio :label="2">
              <el-tag type="danger" size="small">不通过</el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" required>
          <el-input 
            v-model="auditForm.auditComment" 
            type="textarea" 
            :rows="3"
            placeholder="请输入审核意见（必填）"
            :maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitAudit" 
            :loading="auditing"
            :disabled="!auditForm.auditComment">
            提交审核
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { 
  getQualityByTraceCode, 
  createQualityRecord, 
  manualCertify, 
  formatTimestamp, 
  getAuditStatusText,
  submitTemperatureRecord,
  checkQualityStatus
} from '@/utils/QualityCertifier';

export default {
  name: 'QualityMonitor',
  data() {
    return {
      searchForm: {
        traceCode: ''
      },
      qualityData: null,
      isAdmin: true, // 这里应该根据实际权限判断，暂时默认为true
      searching: false,
      submitting: false,
      auditing: false,
      transportScore: 0,
      newRecordForm: {
        productId: '',
        traceCode: '',
        productName: '',
        origin: '',
        harvestTimeDate: '',
        minTemp: 0,
        maxTemp: 30
      },
      auditForm: {
        auditStatus: 1,
        auditComment: ''
      },
      rules: {
        productId: [
          { required: true, message: '请输入产品ID', trigger: 'blur' },
          { type: 'number', message: '产品ID必须为数字', trigger: 'blur' }
        ],
        traceCode: [
          { required: true, message: '请输入溯源码', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        origin: [
          { required: true, message: '请输入产地', trigger: 'blur' }
        ],
        harvestTimeDate: [
          { required: true, message: '请选择收获时间', trigger: 'change' }
        ],
        minTemp: [
          { required: true, message: '请输入最低温度', trigger: 'blur' }
        ],
        maxTemp: [
          { required: true, message: '请输入最高温度', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value <= this.newRecordForm.minTemp) {
                callback(new Error('最高温度必须大于最低温度'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ]
      },
      tempRecordForm: {
        temperature: 20
      },
      submittingTemp: false,
      qualityStatus: null
    };
  },
  methods: {
    // 添加返回主页方法
    goBack() {
      this.$router.push('/');
    },
    // 通过溯源码查询产品质量信息
    searchByTraceCode() {
      if (!this.searchForm.traceCode) {
        this.$message.warning('请输入溯源码');
        return;
      }
      
      this.searching = true;
      getQualityByTraceCode(this.searchForm.traceCode)
        .then(res => {
          if (res && res.productId) {
            this.qualityData = res;
            this.transportScore = this.calculateScore(res.transportScore);
            this.$message.success('查询成功');
            // 查询质量状态
            this.checkQuality();
          } else {
            this.$message.error('未找到相关产品信息');
            this.qualityData = null;
            this.qualityStatus = null;
          }
        })
        .catch(err => {
          console.error('查询失败:', err);
          this.$message.error('查询失败，请稍后重试');
        })
        .finally(() => {
          this.searching = false;
        });
    },
    
    // 重置搜索表单
    resetSearch() {
      this.searchForm.traceCode = '';
      this.qualityData = null;
      this.qualityStatus = null;
    },
    
    // 计算分数星级（将区块链中的分数转换为5星制）
    calculateScore(score) {
      if (!score) return 0;
      // 假设区块链中的分数范围是0-100，转换为0-5星
      return Math.min(5, Math.max(0, score / 20));
    },
    
    // 创建新的质量记录
    submitForm() {
      this.$refs.newRecordForm.validate(valid => {
        if (valid) {
          // 额外检查温度范围
          if (this.newRecordForm.minTemp >= this.newRecordForm.maxTemp) {
            this.$message.error('最高温度必须大于最低温度');
            return false;
          }
          
          this.submitting = true;
          
          // 处理时间戳，将毫秒转为秒
          const harvestTime = Math.floor(this.newRecordForm.harvestTimeDate / 1000);
          
          // 构建参数对象
          const params = {
            productId: this.newRecordForm.productId,
            traceCode: this.newRecordForm.traceCode,
            productName: this.newRecordForm.productName,
            origin: this.newRecordForm.origin,
            harvestTime: harvestTime,
            minTemp: this.newRecordForm.minTemp,
            maxTemp: this.newRecordForm.maxTemp
          };
          
          createQualityRecord(params)
            .then(res => {
              this.submitting = false;
              this.$message.success('质量记录创建成功');
              this.resetForm();
              // 自动查询刚创建的记录
              this.searchForm.traceCode = params.traceCode;
              this.searchByTraceCode();
            })
            .catch(err => {
              this.submitting = false;
              console.error('创建失败:', err);
              this.$message.error('创建失败，请稍后重试');
            });
        } else {
          return false;
        }
      });
    },
    
    // 提交审核结果
    submitAudit() {
      if (!this.qualityData || !this.qualityData.productId) {
        this.$message.error('请先查询产品信息');
        return;
      }
      
      this.auditing = true;
      manualCertify(
        this.qualityData.productId,
        this.auditForm.auditStatus,
        this.auditForm.auditComment
      )
        .then(res => {
          this.auditing = false;
          this.$message.success('审核提交成功');
          // 刷新产品信息
          this.searchByTraceCode();
        })
        .catch(err => {
          this.auditing = false;
          console.error('审核提交失败:', err);
          this.$message.error('审核提交失败，请稍后重试');
        });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.newRecordForm.resetFields();
    },
    
    // 格式化时间显示
    formatTime(timestamp) {
      return formatTimestamp(timestamp);
    },
    
    // 获取审核状态文本
    getAuditStatusText(status) {
      return getAuditStatusText(status);
    },
    
    // 获取状态对应的标签类型
    getStatusType(status) {
      switch (parseInt(status)) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'danger';
        default: return 'info';
      }
    },
    
    // 提交温度记录
    submitTempRecord() {
      if (!this.qualityData || !this.qualityData.traceCode) {
        this.$message.warning('请先选择产品');
        return;
      }
      
      this.submittingTemp = true;
      const timestamp = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
      
      submitTemperatureRecord(
        this.qualityData.traceCode,
        this.tempRecordForm.temperature,
        timestamp
      )
        .then(() => {
          this.$message.success('温度记录提交成功');
          this.checkQuality();
        })
        .catch(err => {
          console.error('温度记录提交失败:', err);
          this.$message.error('温度记录提交失败');
        })
        .finally(() => {
          this.submittingTemp = false;
        });
    },
    
    // 检查质量状态
    checkQuality() {
      if (!this.qualityData || !this.qualityData.traceCode) return;
      
      checkQualityStatus(this.qualityData.traceCode)
        .then(res => {
          this.qualityStatus = res;
        })
        .catch(err => {
          console.error('质量状态检查失败:', err);
          this.$message.error('质量状态检查失败');
        });
    }
  }
};
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.quality-monitor-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.quality-search-card,
.quality-detail-card,
.quality-create-card,
.quality-audit-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.card-header h3 i {
  margin-right: 8px;
  color: #409EFF;
}

.search-form {
  padding: 20px;
}

.product-container {
  padding: 20px;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.product-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.status-tags {
  display: flex;
  align-items: center;
}

.product-content {
  display: flex;
  gap: 30px;
}

.product-main {
  display: flex;
  gap: 30px;
  flex: 2;
}

.product-image {
  width: 300px;
  height: 300px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ebeef5;
}

.product-icon {
  font-size: 120px;
  color: #909399;
}

.product-info {
  flex: 1;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.detail-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.detail-section h4 i {
  margin-right: 5px;
  color: #409EFF;
}

.temperature-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.temp-range, .transport-score, .status-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-label {
  min-width: 80px;
  display: inline-block;
  color: #606266;
  font-weight: 500;
}

.audit-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.audit-comment-box {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.audit-comment {
  margin: 0;
  color: #606266;
  font-size: 14px;
  background-color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  flex: 1;
}

.create-form {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.temp-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.temp-separator {
  color: #909399;
}

.form-buttons {
  margin-top: 30px;
  text-align: center;
}

.audit-form {
  padding: 20px;
}

.el-descriptions {
  margin: 0;
}

.el-descriptions-item__label {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.el-descriptions-item__content {
  color: #303133;
}

.el-tag {
  margin-right: 10px;
}

.el-rate {
  display: inline-block;
}

.temp-record {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.unit {
  margin-left: 5px;
  color: #909399;
}

.quality-status {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.quality-status h5 {
  margin: 0 0 15px 0;
  font-size: 15px;
  color: #303133;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.temp-warning {
  color: #f56c6c;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.temp-warning i {
  margin-right: 3px;
}

.last-check {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.no-margin {
  margin-bottom: 0;
}
</style> 